#include <stdlib.h>
#include <stdio.h>
#include "cli.h"

int main(int argc, char *argv[])
{
	int cmd_len;
	int sock, sockmsg;
	struct sockaddr_in server, servermsg;
	struct hostent *hp;

	sock = socket(AF_INET, SOCK_STREAM, 0);
	sockmsg = socket(AF_INET, SOCK_STREAM, 0);

	if (sock < 0 || sockmsg < 0) {
		perror("opening stream socket error");
		exit(1);
	}

	hp = gethostbyname(argv[1]);
	if (hp == 0) {
		fprintf(stderr, "%s: unknown host\n", argv[1]);
		exit(2);
	}

	server.sin_family = AF_INET;
	server.sin_port = htons(atoi(argv[2]));
	server.sin_addr = *(struct in_addr *)hp->h_addr;
	/* memcpy((char *)&server.sin_addr, (char *)hp->h_addr, hp->h_length); */

	servermsg.sin_family = AF_INET;
	servermsg.sin_port = htons(atoi(argv[2]) + 1);
	servermsg.sin_addr = *(struct in_addr *)hp->h_addr;
	/* memcpy((char *)&servermsg, (char *)hp->h_addr, hp->h_length); */

	if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0 || 
			connect(sockmsg, (struct sockaddr *)&servermsg, sizeof(servermsg)) < 0) {
		perror("connecting stream socket error");
		exit(1);
	}

	/* Get command frome command line and do just the action */
	while (TRUE) {
		memset(user_cmd, '\0', 10);
		memset(cmd_arg, '\0', 20);

		/* First get the input character by user */
		printf("command: ");
		scanf("%s", user_cmd);
		cmd_len = strlen(user_cmd);

		/* Then get the command character and the argument */
		if (strcmp(user_cmd, "quit") == 0) {
			cmd_quit(sock, sockmsg);
			close(sockmsg);
			close(sock);
			printf("connection closed\n\n");
			exit(0);
		}
		else if (strcmp(user_cmd, "?") == 0) {
			cmd_help(sock, sockmsg);
		}
		else if (strcmp(user_cmd, "pwd") == 0) {
			cmd_pwd(sock, sockmsg);
		}
		else if (strcmp(user_cmd, "dir") == 0) {
			cmd_dir(sock, sockmsg);
		}
		else if (strcmp(user_cmd, "cd") == 0) {
			/*input command argument */
			scanf("%s", cmd_arg);
			cmd_cd(sock, sockmsg, cmd_arg);
		}
		else if (strcmp(user_cmd, "cd..") == 0) {
			cmd_cdback(sock, sockmsg);
		}
		else if (strcmp(user_cmd, "get") == 0) {
			scanf("%s", cmd_arg);
			cmd_get(sock, sockmsg, cmd_arg);
		}
		else if (strcmp(user_cmd, "put") == 0) {
			scanf("%s", cmd_arg);
			cmd_put(sock, sockmsg, cmd_arg);
		}
		else {
			printf("bad command!\n");
		}
	}
}
